import axios from './http'
import { AxiosRequestConfig } from 'axios'

interface FcResponse<T> {
  result: T
  code: number
  message: string
}

type config = {
  clearFn?: (data: FcResponse<any>) => any
} & AxiosRequestConfig<any>

const get = <T = any>(api: string, params: { [key: string]: any } = {}, config: config = {}): Promise<T> => {
  config.params = params
  return new Promise((resolve, reject) => {
    axios.get<FcResponse<T>>(api, config)
    .then(response => {
      const { data } = response
      let res: T
      if(config.clearFn) {
        res = config.clearFn(data)
      } else res = data.result
      resolve(res)
    })
    .catch(error => {
      reject(error)
    })
  })
}

const post = <T = any>(api: string, data: { [key: string]: any } = {}, config: config = { headers: {} }): Promise<T> => {
  if (config.headers && !config.headers['Content-Type']) config.headers['Content-Type'] = 'application/json'
  return new Promise((resolve, reject) => {
    axios.post<FcResponse<T>>(api, JSON.stringify(data), config)
      .then(response => {
        const { data } = response
        let res: T
        if (config.clearFn) {
          res = config.clearFn(data)
        } else res = data.result
        resolve(res)
      })
      .catch(error => {
        reject(error)
      })
  })
}

const put = <T = any>(api: string, data: { [key: string]: any } = {}, config: config = { headers: {} }): Promise<T> => {
  if (config.headers && !config.headers['Content-Type']) config.headers['Content-Type'] = 'application/json'
  return new Promise((resolve, reject) => {
    axios.put<FcResponse<T>>(api, JSON.stringify(data), config)
      .then(response => {
        const { data } = response
        let res: T
        if (config.clearFn) {
          res = config.clearFn(data)
        } else res = data.result
        resolve(res)
      })
      .catch(error => {
        reject(error)
      })
  })
}

const del = <T = any>(api: string, params: { [key: string]: any } = {}, config: config = { headers: {} }): Promise<T> => {
  config.params = params
  return new Promise((resolve, reject) => {
    axios.delete<FcResponse<T>>(api, config)
      .then(response => {
        const { data } = response
        let res: T
        if (config.clearFn) {
          res = config.clearFn(data)
        } else res = data.result
        resolve(res)
      })
      .catch(error => {
        reject(error)
      })
  })
}

export const http = { get, post, put, delete: del }


